用於雙向的單次訊息傳遞,包括發送訊息、接收訊息兩個功能
經過以上的實作,其實兩端的通訊步驟都差不多,首先在兩端建立想要
Channel
並指定名稱,且在兩端通道名稱需對應,傳送端對接收端發訊息來執行Channel
的對應的動作(執行Native 端方法,或監聽Native 端訊息,亦或發送訊息至Native 端訊息),接收端建立完對應的Channel
後要建立handler
處理從傳送端來的訊息執行對應動作,並回傳結果
Flutter 端
新增BasicMessageChannel
並指定名稱,且新增要從Flutter 端傳訊息給Native 端的方法,並回傳Native 端要回覆的訊息
lib/batterylevel.dart
:
static const BasicMessageChannel _messageChannel =
const BasicMessageChannel('chat_message', StringCodec());
static Future<String> messageResponse(String message) async {
final String response = await _messageChannel.send(message);
return response;
}
Native 端(Android):
android/.../BatterylevelPlugin.kt
:
private lateinit var messageChannel: BasicMessageChannel<String>
override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
//Added
messageChannel = BasicMessageChannel(
flutterPluginBinding.binaryMessenger,
"chat_message",
StringCodec.INSTANCE
)
messageChannel.setMessageHandler { message, reply ->
val response = if(message.isNullOrEmpty()) "" else "Android 收到:$message"
reply.reply(response)
}
}
override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
//Added
messageChannel.setMessageHandler(null)
}
Native 端(iOS):
ios/Classes/RandomNumberStreamHandler.swift
public class SwiftBatterylevelPlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
//Added
let messageChannel = FlutterBasicMessageChannel(name: "chat_message", binaryMessenger: registrar.messenger(),codec: FlutterStringCodec.sharedInstance())
messageChannel.setMessageHandler {
(message: Any?, reply: FlutterReply) -> Void in
reply((message as! String) != "" ? "iOS 收到:\(message as! String)" : "");
}
}
}
以上就完成運用Platform Channel
來實作平台兩端的通訊了,[範例程式都在這](